package cn.sdnu.database.service;

import cn.sdnu.database.controller.DbController;
import cn.sdnu.database.utils.TableGenerator;
import cn.sdnu.database.utils.Utils;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author Master_Joe qiaoguangtong@aliyun.com
 */
public class Show {
	private static Show show = null;
	private static ReentrantLock lock = new ReentrantLock();

	private Show() {

	}

	public static Show getInstance() {
		if (show == null) {
			lock.lock();
			try {
				if (show == null) {
					show = new Show();
				}
			} finally {
				lock.unlock();
			}
		}
		return show;
	}

	public void sqlHandle(String sql) {
		if (sql.startsWith("show databases")) {
			showDatabases();
		} else if (sql.startsWith("show tables")) {
			if (Use.getInstance().getDatabaseUsed() != null) {
				showTables();
			} else {
				System.out.println("ERROR: No database selected");
			}
		} else {
			System.out.println("Error: You have some syntax error, please try again");
		}
	}

	/**
	 * show tables
	 */
	private void showTables() {
		List<String> tables = Utils.getTables(Use.getInstance().getDatabaseUsed());
		if (tables.size() == 0) {
			System.out.println("Empty set\n");
			return;
		}
		List<String> headersList = new ArrayList<String>();

		String header = "Tables_in_" + Use.getInstance().getDatabaseUsed();

		headersList.add(header);

		List<List<String>> rowsList = new ArrayList<List<String>>();

		for (String table : tables) {
			ArrayList<String> simpleRow = new ArrayList<String>();
			simpleRow.add(table);
			rowsList.add(simpleRow);
		}
		System.out.println(TableGenerator.generateTable(headersList, rowsList));
		System.out.println(rowsList.size() + " rows in set\n");

	}

	/**
	 * 显示数据库
	 */
	private void showDatabases() {
		File file = new File(DbController.TEST_BASE);
		File[] files = file.listFiles();
		List<String> headerList = new ArrayList<>();
		headerList.add("Databases");

		List<List<String>> rowsList = new ArrayList<>();
		for (int i = 0; i < files.length; i++) {
			ArrayList<String> row = new ArrayList<>();
			if (files[i].isDirectory()) {
				row.add(files[i].getName());
				rowsList.add(row);
			} else {

			}
		}

		System.out.println(TableGenerator.generateTable(headerList, rowsList));
		System.out.println(rowsList.size() + " rows in set\n");

	}

}
